<template>
  <div class='container'>
    <el-card class="box-card">
      <!-- 搜索框 -->
      <el-form :model="filterParams" ref="ruleForm" :inline="true" class="demo-form-inline">
        <el-form-item class="subject" prop='directoryName' label="目录名称：">
          <el-input style="width:175px" v-model="filterParams.directoryName"></el-input>
        </el-form-item>
        <el-form-item prop='state' label="状态：">
          <el-select v-model="filterParams.state" style="width:175px" placeholder="请选择状态">
            <el-option v-for='item in status ' :key="item.value" :label="item.label" :value="item.value"></el-option>
            <!-- <el-option label="启用" value="0"></el-option>
            <el-option label="禁用" value="1"></el-option> -->
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
          <el-button size="small" @click="handleChange" type="primary">查询</el-button>
        </el-form-item>
        <!-- 返回学科按钮 -->
        <el-button @click="back" style="margin-left: 130px;" icon="el-icon-back" type="text" v-if="$route.query.id">返回学科</el-button>
        <!-- <el-button style="margin-left: 130px;" icon="el-icon-back" type="text" v->返回学科</el-button> -->

        <!-- 添加目录按钮 -->
        <el-button @click="addNew" class="filter-item fr" size="small" style="margin-left: 10px;" type="success" icon="el-icon-edit">新增用户</el-button>
      </el-form>
      <!-- 消息 -->
      <el-alert class="alert" :title="total" type="info" show-icon></el-alert>
      <!-- 表单 -->
      <el-table :data="list" style="width: 100%">
        <el-table-column type="index" label="序号">

          <!-- <div v-for="(item,index) in filterParams.pagesize" :key='item.id'>
            {{index}}</div> -->

        </el-table-column>
        <el-table-column prop="subjectName" label="所属学科">
        </el-table-column>
        <el-table-column prop="directoryName" label="目录名称">
        </el-table-column>
        <el-table-column prop="username" label="创建者">
        </el-table-column>
        <el-table-column prop="addDate" width="180px" label="创建日期">
          <template v-slot='scope'>
            <p>{{scope.row.addDate|formatTime}}</p>
          </template>
        </el-table-column>
        <el-table-column prop="totals" label="面试题数量">
        </el-table-column>
        <el-table-column prop="state" label="状态">
          <template v-slot='scope'>
            {{scope.row.state===1?'已启用':'已禁用'}}
          </template>
        </el-table-column>
        <el-table-column prop="address" width="180px" label="操作">
          <template v-slot='scope'>
            <div class="btn">
              <!-- 启用/禁用 -->
              <el-button @click="toggleState(scope.row)" type="text">{{scope.row.state===1?'禁用':'启用'}}</el-button>
              <!-- 编辑 -->
              <el-button type="text" v-if="!scope.row.state" @click="editSubject(scope.row)" :dialogVisible='dialogVisible'>
                编辑
              </el-button>
              <el-button type="text" v-else disabled>
                编辑
              </el-button>
              <!-- 删除按钮 -->
              <el-button type="text" v-if="!scope.row.state" @click="remove(scope.row)">删除</el-button>
              <el-button type="text" v-else disabled>删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination">
        <div class="pages">
          <el-pagination background @size-change='changePagerSize' @current-change="changePager" :current-page="Number(filterParams.page)" :total="totals" :page-size="Number(filterParams.pagesize)" :page-sizes="[5,10,20, 50]" layout="->,prev, pager, next, sizes, jumper"></el-pagination>
        </div>
      </div>
      <!-- 弹出层 -->
      <el-dialog :title="title" :visible.sync="dialogVisible">
        <div class="text item">
          <el-form :model="newInfo" ref="dialog" v-model="newInfo" label-width="100px" class="demo-ruleForm">
            <el-form-item prop="subjectID" label="目录学科">
              <el-select v-model="newInfo.subjectID" value='' placeholder="请选择活动区域">
                <el-option v-for="item in subject" :key="item.value" :label='item.label' :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="directoryName" label="目录名称">
              <el-input v-model="newInfo.directoryName"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="cancle">取消</el-button>
              <el-button @click="submit" type="primary">确认</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
      <!-- <el-pagination background @current-change="changePager" :current-page="Number(filterParams.page)" :total="Number(total)" :page-size="Number(filterParams.pagesize)" :page-sizes="[10,20,30, 50]" layout="sizes, prev, pager, next, jumper"></el-pagination> -->
      <!-- <el-pagination style="margin-top:20px" background layout="prev, pager, next, sizes, jumper" :total="Number(total)" :page-sizes=[5,10,20,50] :current-page="Number(filterParams.page)" :page-size="Number(filterParams.pagesize)" @current-change="changePager"></el-pagination> -->
    </el-card>
  </div>

</template>

<script>
// 导入moment
import moment from 'moment'
import { status } from '@/api/hmmm/constants.js'
import { list, changeState, add, detail, update, remove } from '@/api/hmmm/directorys.js'
import { simple } from '@/api/hmmm/subjects.js'
export default {
  data () {
    return {
      // id: null,
      // 状态
      status: status,
      // 对话框（弹出层）题目
      title: '添加目录',
      // 添加  编辑目录传参
      newInfo: {
        directoryName: '',
        subjectID: null,
        id: null
      },
      // 目录详情（编辑中的数据）
      // details: {
      //   id: null,
      //   directoryName: '',
      //   subjectID: null
      // },
      // 状态
      // status: [],
      total: '0',
      totals: 0,
      // 目录列表数组
      list: [],
      // 目录学科数组
      subject: [],
      // dialogVisible对话框状态
      dialogVisible: false,
      // 传参 (获取目录列表)
      filterParams: {
        subjectID: null,
        directoryName: null,
        state: null,
        page: 1,
        pagesize: 10
      }

    }
  },
  // 时间过滤器
  filters: {
    formatTime (time) {
      return moment(time).format('yyyy-MM-DD HH:MM:ss')
    }
  },
  methods: {
    back () {
      this.$router.push('/subjects/list')
    },
    // 新增标签
    addNew () {
      this.dialogVisible = true
      this.title = '添加标签'
    },
    // 删除操作
    remove (row) {
      this.$confirm('此操作将永久删除 是否确认删除？', '提示', {
        type: 'warning'
      }).then(async () => {
        await remove(row)
        this.handleDirectorysList()
      }).catch((e) => {
        if (e === 'cannel') {
          console.log('取消删除')
        } else {
          this.$message.error('删除失败')
        }
      })
    },
    // 取消按钮
    async cancle () {
      // 将id清空  当点击
      this.dialogVisible = false
    },
    // 获取目录详情信息（编辑里面的信息）
    async editSubject (row) {
      // 弹窗
      this.dialogVisible = true
      this.title = '编辑目录'
      try {
        const ret = await detail(row)
        console.log(ret)
        this.newInfo = ret.data
      } catch (error) {
        console.log(error)
        this.$message.error('获取目录信息失败')
      }
    },
    // 清除按钮(重置)
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    // 目录添加 目录修改提交  如果携带id
    async submit () {
      if (this.newInfo.id) {
        try {
          // 发送修改请求
          await update(this.newInfo)
          // 清空id值 这样当点击添加的时候就不会出现数据回填了
          this.newInfo.id = null
          // 重置
          this.$refs.dialog.resetFields()
          this.dialogVisible = false
          // 刷新页面
          this.handleDirectorysList()
        } catch (error) {
          console.log(error)
          this.$message.error('编辑目录失败')
        }
      } else {
        try {
          // 调接口
          await add(this.newInfo)
          // 清空id值 这样当点击添加的时候就不会出现数据回填了
          this.newInfo.id = null
          // 重置
          this.$refs.dialog.resetFields()
          // 更新页面
          this.handleDirectorysList()
          this.dialogVisible = false
        } catch (error) {
          console.log(error)
          this.$message.error('添加目录失败')
        }
      }
    },
    // 获取学科列表
    async getSubject () {
      try {
        const ret = await simple()
        console.log(ret)
        this.subject = ret.data
        // console.log(ret.data)
      } catch (error) {
        console.log(error)
        this.$message.error('获取目录信息失败')
      }
    },
    // 切换状态
    async toggleState (row) {
      // console.log(row)
      try {
        const changeVal = row.state === 1 ? 0 : 1
        const res = await changeState({
          id: row.id,
          state: changeVal
        })

        if (res.data.success) {
          row.state = changeVal
        }
        // row.state = row.state === 0 ? 1 : 0
      } catch (error) {
        console.log(error)
        this.$message.error('切换状态失败')
      }
    },
    // 当改变每页多少条时
    async changePagerSize (newPageSize) {
      this.filterParams.pagesize = newPageSize
      this.handleDirectorysList()
    },
    // 页码发生变化
    async changePager (newPage) {
      this.filterParams.page = newPage
      this.handleDirectorysList()
    },
    // 点击查询
    async handleChange (pa) {
      // console.log(pa)
      this.filterParams.page = 1
      this.handleDirectorysList()
    },
    // 获取目录列表
    async handleDirectorysList () {
      try {
        const ret = await list(this.filterParams)
        console.log(ret)
        // console.log(ret)
        this.list = ret.data.items
        this.total = `数据一共有${ret.data.counts}条`
        this.totals = ret.data.counts
      } catch (error) {

      }
    }
  },
  watch: {
    // $route (to) {
    //   if (!to.query.id) {
    //     // console.log('hgj')
    //     this.id = false
    //     // console.log(this.id)
    //   }
    // }
  },
  // 生命周期
  created () {
    // 获取目录列表
    this.handleDirectorysList()
    console.log(this.$route.query.id)
    // 判断是否传入id
    if (this.$route.query.id) {
      this.filterParams.subjectID = this.$route.query.id
      // 当有id的时候 将id值传给参数id 进行显示与隐藏返回学科按钮
      // this.id = true
      this.handleDirectorysList()
    }
    // 获取学科列表
    this.getSubject()
    // this.detail()
  }
}
</script>

<style scoped lang='scss'>
.container {
  margin-top: 15px;
  margin-left: 10px;
  .subject {
    margin-right: 50px;
  }
  .pagination {
    margin-top: 10px;
  }
  .alert {
    margin: 0 0 10px 0;
  }

  // .btn {
  //   .edit {
  //     border: 0;
  //   }
  //   span {
  //     font-size: 14px;
  //     font-weight: 700;
  //     color: #46a0fc;
  //     cursor: pointer;
  //     margin-left: 5px;
  //   }
  // }
}
</style>
